package com.gec.common;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gec.vo.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {

    /**
     * @param httpServletRequest  请求对象
     * @param httpServletResponse 应答对象
     * @param authentication      验证用户信息成功后的封装类
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //在登录用户信息验证成功后执行的方法,总接口有默认实现x
        httpServletResponse.setContentType("text/json;charset=utf-8");

        Result result = new Result();
        result.setCode(0);
        result.setError(200);
        result.setMsg("登录成功");
        ServletOutputStream out = httpServletResponse.getOutputStream();

        //json对象
        ObjectMapper om = new ObjectMapper();
        om.writeValue(out, result);

        out.flush();
        out.close();
    }
}
